package net.hn.hnms.biz.energy.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import net.hn.hnms.biz.energy.domain.WaterSupplyCompany;
import net.hn.hnms.biz.energy.mapper.StatisticsMapper;
import net.hn.hnms.biz.energy.request.WaterSupplyCompanyReq;
import net.hn.hnms.biz.energy.service.StatisticsService;
import net.hn.hnms.biz.energy.vo.HydropowerVo;
import net.hn.hnms.biz.energy.vo.MonthValue;
import net.hn.hnms.sys.common.core.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static net.hn.hnms.sys.common.core.utils.DateUtils.getMoMDateRange;

@Service
public class StatisticsServiceImpl extends BaseService<WaterSupplyCompanyReq, WaterSupplyCompany> implements StatisticsService {
    @Autowired
    private StatisticsMapper statisticsMapper;
    @Override
    public HydropowerVo getWaterStatistics(String mineCode) {
        //按月份统计水
        Map<String,Object> waterConsumptionMap = statisticsMapper.getWaterConsumptionMonth(mineCode);
        HydropowerVo vo = new HydropowerVo();
        if(waterConsumptionMap != null && !waterConsumptionMap.isEmpty()){
            String waterConsumption = waterConsumptionMap.get("waterconsumption") == null ? "0" : waterConsumptionMap.get("waterconsumption").toString();
            BigDecimal wa = new BigDecimal(waterConsumption).divide(new BigDecimal("10000"),2, BigDecimal.ROUND_CEILING);
            vo.setMonthWater(wa);
        }
        //按月份统计电
        Map<String,Object> settleElectricConsumptionMap = statisticsMapper.getSettleElectricConsumptionMonth(mineCode);
        if(settleElectricConsumptionMap != null && !settleElectricConsumptionMap.isEmpty()){
            String settleelectricconsumption = settleElectricConsumptionMap.get("settleelectricconsumption") == null ? "0" : settleElectricConsumptionMap.get("settleelectricconsumption").toString();
            BigDecimal se = new BigDecimal(settleelectricconsumption).divide(new BigDecimal("10000"),2, BigDecimal.ROUND_CEILING);
            vo.setMonthElectricity(se);
        }
        //按年份统计水
        Map<String,Object> waterConsumptionYearMap = statisticsMapper.getWaterConsumptionYear(mineCode);
        if(waterConsumptionYearMap != null && !waterConsumptionYearMap.isEmpty()){
            String waterConsumption = waterConsumptionYearMap.get("waterconsumption") == null ? "0" : waterConsumptionYearMap.get("waterconsumption").toString();
            BigDecimal wa = new BigDecimal(waterConsumption).divide(new BigDecimal("10000"),2, BigDecimal.ROUND_CEILING);
            vo.setYearWater(wa);
        }
        //按年份统计电
        Map<String,Object> settleElectricConsumptionYearMap = statisticsMapper.getSettleElectricConsumptionYear(mineCode);
        if(settleElectricConsumptionYearMap != null && !settleElectricConsumptionYearMap.isEmpty()){
            String settleelectricconsumption = settleElectricConsumptionYearMap.get("settleelectricconsumption") == null ? "0" : settleElectricConsumptionYearMap.get("settleelectricconsumption").toString();
            BigDecimal se = new BigDecimal(settleelectricconsumption).divide(new BigDecimal("10000"),2, BigDecimal.ROUND_CEILING);
            vo.setYearElectricity(se);
        }
        return vo;
    }


    /**
     * 生产成本分析-生产用水
     *
     * @param year  年份
     * @param month 月份
     * @return List<MonthValue>
     */
    @Override
    public Map<String, List<MonthValue>> costWaterByYear(Integer year, Integer month, String mineCode) {
        Date[] dateRange = DateUtils.getDateRangeUtilNow(year, month);
        Map<String, Date[]> stringMap = DateUtils.calculateComparisonDateRange(year);
        Date date = stringMap.get("yearOnYear")[0];
        Date date1 = stringMap.get("yearOnYear")[1];
        Date[] moMDateRange = getMoMDateRange(dateRange[0], dateRange[1]);
        List<String> placeList = statisticsMapper.waterPlaceList(mineCode);
        List<MonthValue> costOfMonth = statisticsMapper.costWaterByYear(dateRange[0], dateRange[1],mineCode);
        List<MonthValue> costOfMonthYoy = statisticsMapper.costWaterByYear(date, date1,mineCode);
        List<MonthValue> costOfMonthMom = statisticsMapper.costWaterByYear(moMDateRange[0], moMDateRange[1],mineCode);
        Map<String, List<MonthValue>> result = new HashMap<>();

        for (String s : placeList) {
            Map<Integer, MonthValue> tempMap = costOfMonth.stream().filter(o -> StrUtil.equals(o.getName(), s)).collect(Collectors.toMap(MonthValue::getMonth, Function.identity()));
            Map<Integer, MonthValue> tempMapYoy = costOfMonthYoy.stream().filter(o -> StrUtil.equals(o.getName(), s)).collect(Collectors.toMap(MonthValue::getMonth, Function.identity()));
            Map<Integer, MonthValue> tempMapMom = costOfMonthMom.stream().filter(o -> StrUtil.equals(o.getName(), s)).collect(Collectors.toMap(MonthValue::getMonth, Function.identity()));

            Map<Integer, MonthValue> adjustedMoMenergyMap = tempMapMom.entrySet().stream()
                    .collect(Collectors.toMap(entry -> (entry.getKey() % 12) + 1, Map.Entry::getValue));

            List<MonthValue> resultList = new ArrayList<>();
            for (int i = 1; i < DateUtil.month(dateRange[1]) + 2; i++) {
                MonthValue currentMonthValue = tempMap.getOrDefault(i, new MonthValue(i));
                MonthValue yoyMonthValue = tempMapYoy.get(i);
//                MonthValue momMonthValue = tempMapMom.get(i);
                if (yoyMonthValue != null) {
                    currentMonthValue.setTotal2(yoyMonthValue.getTotal());
                }
                MonthValue Momenergy = adjustedMoMenergyMap.getOrDefault(i, new MonthValue(i));
                if (Momenergy != null) {
                    currentMonthValue.setTotal3(Momenergy.getTotal());
                }
                resultList.add(currentMonthValue);
            }
            result.put(s, resultList);
        }
        return result;
    }




    /**
     * 生产成本分析-生产用水
     *
     * @param year  年份
     * @param month 月份
     * @return List<MonthValue>
     */
    @Override
    public Map<String, BigDecimal> costOfPlace(Integer year, Integer month,String mineCode) {
        Date[] dateRange = DateUtils.getDateRange(year, month);
        Map<String, BigDecimal> result = new HashMap<>();
        List<String> placeList = statisticsMapper.waterPlaceList(mineCode);
        List<Map<String, String>> costOfPlaceList = statisticsMapper.costOfPlace(dateRange[0], dateRange[1],mineCode);
        for (String s : placeList) {
            result.put(s, BigDecimal.ZERO);
            Iterator<Map<String, String>> iterator = costOfPlaceList.listIterator();
            while (iterator.hasNext()) {
                Map<String, String> stringStringMap = iterator.next();
                String place = stringStringMap.get("place");
                if (StrUtil.equals(place, s)) {
                    BigDecimal total = Convert.toBigDecimal(stringStringMap.get("total"),BigDecimal.ZERO);
                    result.put(place, total);
                    iterator.remove();
                }
            }
        }
        return result;
    }
}
